<template>
  <div>
    <h3>客户管理表格</h3>
    <el-input
        placeholder="请输入姓名"
        v-model="searchQuery"
        style="width: 200px; margin-right: 10px;"
        clearable
        @clear="fetchCustomers"
    />
    <el-button type="primary" @click="searchCustomers">搜索</el-button>
    <el-button type="primary" @click="openDialog">添加客户</el-button>
    <el-table :data="customers" style="width: 100%; margin-top: 20px;">
      <!-- 表格列定义 -->
      <el-table-column prop="id" label="ID" width="180"></el-table-column>
      <el-table-column prop="name" label="姓名" width="180"></el-table-column>
      <el-table-column prop="address" label="地址" width="180"></el-table-column>
      <el-table-column prop="area" label="区域" width="180"></el-table-column>
      <el-table-column prop="contacts" label="联系人" width="180"></el-table-column>
      <el-table-column prop="number" label="电话" width="180"></el-table-column>
      <el-table-column prop="manager" label="经理" width="180"></el-table-column>
      <el-table-column prop="managerNumber" label="经理电话" width="180"></el-table-column>
      <el-table-column prop="date" label="填写时间" width="180"></el-table-column>
      <el-table-column prop="state" label="状态" width="180"></el-table-column>
      <el-table-column prop="operator" label="操作员" width="180"></el-table-column>
      <el-table-column label="操作" width="180">
        <template v-slot="scope">
          <el-button size="small" @click="editCustomer(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteCustomer(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="isEdit ? '编辑客户' : '添加客户'" v-model="dialogVisible">
      <el-form :model="newCustomer" :rules="rules" ref="customerForm">
        <!-- 表单项定义 -->
        <el-form-item label="姓名" :label-width="formLabelWidth" prop="name">
          <el-input v-model="newCustomer.name"></el-input>
        </el-form-item>
        <el-form-item label="地址" :label-width="formLabelWidth" prop="address">
          <el-input v-model="newCustomer.address"></el-input>
        </el-form-item>
        <el-form-item label="区域" :label-width="formLabelWidth" prop="area">
          <el-select v-model="newCustomer.area" placeholder="请选择区域">
            <el-option v-for="area in areas" :key="area.id" :label="area.name" :value="area.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" :label-width="formLabelWidth" prop="contacts">
          <el-input v-model="newCustomer.contacts"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth">
          <el-input v-model="newCustomer.number"></el-input>
        </el-form-item>
        <el-form-item label="经理" :label-width="formLabelWidth">
          <el-input v-model="newCustomer.manager"></el-input>
        </el-form-item>
        <el-form-item label="经理电话" :label-width="formLabelWidth">
          <el-input v-model="newCustomer.managerNumber"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addOrUpdateCustomer">确定</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import {ElMessage} from 'element-plus';

export default {
  data() {
    return {
      customers: [],
      areas: [],
      dialogVisible: false,
      isEdit: false,
      searchQuery: '',
      newCustomer: {
        name: '',
        address: '',
        area: '',
        contacts: '',
        number: '',
        manager: '',
        managerNumber: '',
        state: '',
        operator: ''
      },
      formLabelWidth: '120px',
      rules: {
        name: [{required: true, message: '请输入姓名', trigger: 'blur'}],
        address: [{required: true, message: '请输入地址', trigger: 'blur'}],
        area: [{required: true, message: '请选择区域', trigger: 'change'}],
        contacts: [{required: true, message: '请输入联系人', trigger: 'blur'}]
      }
    };
  },
  created() {
    this.fetchCustomers();
    this.fetchAreas();
  },
  methods: {
    fetchCustomers() {
      axios.get('http://localhost:8081/api/customer/getall')
          .then(response => {
            this.customers = response.data;
          })
          .catch(error => {
            console.error("There was an error fetching the customers!", error);
          });
    },
    fetchAreas() {
      axios.get('http://localhost:8081/api/customer/areas')
          .then(response => {
            this.areas = response.data;
          })
          .catch(error => {
            console.error("There was an error fetching the areas!", error);
          });
    },
    searchCustomers() {
      axios.get(`http://localhost:8081/api/customer/get/${this.searchQuery}`)
          .then(response => {
            this.customers = response.data;
          })
          .catch(error => {
            console.error("There was an error searching the customers!", error);
          });
    },
    openDialog() {
      this.isEdit = false;
      this.dialogVisible = true;
      this.resetCustomer();
    },
    editCustomer(customer) {
      this.isEdit = true;
      this.dialogVisible = true;
      this.newCustomer = {...customer};
    },
    addOrUpdateCustomer() {
      this.$refs.customerForm.validate(valid => {
        if (valid) {
          if (this.isEdit) {
            this.newCustomer.state = '修改';
            axios.put('http://localhost:8081/api/customer/update', this.newCustomer)
                .then(() => {
                  this.dialogVisible = false;
                  this.fetchCustomers();
                  this.resetCustomer();
                  ElMessage.success('客户更新成功');
                })
                .catch(error => {
                  console.error("There was an error updating the customer!", error);
                  ElMessage.error('客户更新失败');
                });
          } else {
            this.newCustomer.state = '新建';
            axios.post('http://localhost:8081/api/customer/add', this.newCustomer)
                .then(() => {
                  this.dialogVisible = false;
                  this.fetchCustomers();
                  this.resetCustomer();
                  ElMessage.success('客户添加成功');
                })
                .catch(error => {
                  console.error("There was an error adding the customer!", error);
                  ElMessage.error('客户添加失败');
                });
          }
        }
      });
    },
    deleteCustomer(id) {
      axios.delete(`http://localhost:8081/api/customer/delete/${id}`)
          .then(() => {
            this.fetchCustomers();
            ElMessage.success('客户删除成功');
          })
          .catch(error => {
            console.error("There was an error deleting the customer!", error);
            ElMessage.error('客户删除失败');
          });
    },
    resetCustomer() {
      const username = localStorage.getItem('username');
      this.newCustomer = {
        name: '',
        address: '',
        area: '',
        contacts: '',
        number: '',
        manager: '',
        managerNumber: '',
        state: '',
        operator: username || ''
      };
    }
  }
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
